package example.string;

/**
 * Created by lenovo on 2016/11/4 0004.
 * String.intern()优化字符串
 */
public class Intern {
    public static void main(String[] args) {
        String variables[] = new String[50000];
        for( int i=0;i <50000;i++){
            variables[i] = "s"+i;
        }
        long startTime0 = System.nanoTime();
        for(int i=0;i<50000;i++){
            variables[i] = "hello";
        }
        long endTime0 = System.nanoTime();
        System.out.println("Creation time"
                + " of String literals : "+ (endTime0 - startTime0)
                + " ns" );
        long startTime1 = System.nanoTime();
        for(int i=0;i<50000;i++){
            variables[i] = new String("hello");
        }
        long endTime1 = System.nanoTime();
        System.out.println("Creation time of"
                + " String objects with 'new' key word : "
                + (endTime1 - startTime1)
                + " ns");
        long startTime2 = System.nanoTime();
        for(int i=0;i<50000;i++){
            variables[i] = new String("hello");
            variables[i] = variables[i].intern();
        }
        long endTime2 = System.nanoTime();
        System.out.println("Creation time of"
                + " String objects with intern(): "
                + (endTime2 - startTime2)
                + " ns");
    }
}
